import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router/index'
import { localGet } from './index'
import config from '~/config'
import {login, logout} from '../assets/login/tologin'
let errorNum = 0;

var apiMap = {}

function times (){
  if (Object.keys(apiMap).length > 0){
    // store.state.pageHasLoading = true
  }
}

const httpServerCancel = ()  => {
  Object.keys(apiMap).forEach(function (key) {
    apiMap[key].httpDefaultOpts.source.cancel('请求已取消！')
  });
}
function addTime(httpDefaultOpts) {
  let id = httpDefaultOpts.url
  if (apiMap[id]){
    delete eval(apiMap)[id]
    if (Object.keys(apiMap).length === 0) {
      // store.state.pageHasLoading = false
      window.clearInterval(timeController)
      if (errorNum >= 1) {
        errorNum = 0;
        // store.state.errortime = Math.random() * 10000000;
      }
    }
  } else {
    if (httpDefaultOpts.url){
      httpDefaultOpts.isSubAllowed = false
    }
    apiMap[id] = {httpDefaultOpts: httpDefaultOpts}
  }
}
// 返回拦截器配置
axios.interceptors.response.use(response => {
  if(response.headers != null && response.headers['content-type'] === 'application/octet-stream;charset=UTF-8') {
    response.headers['Content-Type'] = response.headers['content-type'];
  }    
  response.config.url = response.config.url.replace(response.config.baseURL, "");
  // hideLoading();
  addTime(response.config);
  if(response.data && response.data.data && response.data.data.total) {
    response.data.data.total = Number(response.data.data.total);
  }
  return response
}, error => {
  error.config.url = error.config.url.replace(error.config.baseURL, "");
  errorNum += 1;
  addTime(error.config);
  return Promise.resolve(error.response)
})

// 成功后返回
function successState(res) {
  //加入loading
  //统一判断后端返回的错误码
  if (res && res.data.code != 0 && res.data.code != '0') {
    // store.state.alertText = res.data.msg || '网络异常，请检查网络后重试！';
    // store.state.isAlert = true;
    return res
  } else if (!res){
    return {data:{code: '-1', msg: '网络异常，请重试！'} }
  } else {
    return res
  }
}
// http请求
const httpServer = (opts, data) => {
  if (!localStorage.getItem('userinfo') || !JSON.parse(localStorage.getItem('userinfo')).logined) {
	      //已经登录了   不需要登录
    var token = window.location.search.split('=')[1];
    if(token){
      //若有token，表示用户登录了，需要通过token去换取用户登录信息
      login();
    }else{
      //去执行登录
      logout();
    }
	  return ;
  }
  opts.method = opts.method ? opts.method.toLowerCase() : "get";
  data = JSON.parse(JSON.stringify(data).replace(/(^\s*)|(\s*$)/g, "")); // 去掉空格
  let userInfo = JSON.parse(localStorage.getItem('userinfo'));// 测试不需要登录
  // let userInfo = {
  //   token: "666"
  // };
  // 测试不需要登录
  // if (global.unitInformation === undefined) {
  //   global.uToken = userInfo.token;
  // }
  let HYtimestamp = (new Date()).getTime();
  let Public = { //公共参数
    "HYtimestamp": HYtimestamp
  }
  let pversion = ""
  let ss = "?";
  if(opts.url.indexOf("?") != -1)
  {
    ss = "&";
  }
  let httpDefaultOpts = { //http默认配置
    method: opts.method,
    baseURL: "/api", // 接口公共部分
    responseType: opts.responseType ? opts.responseType : "",
    url: opts.url + ss + Public.HYtimestamp,
    timeout: 30000,
    params: typeof data === "string" ? "" : Object.assign(Public, data),
    data: Object.assign(Public, data),
    headers: opts.method == "get" ? { //配置请求头数据
      "X-Requested-With": "XMLHttpRequest",
      "Accept": "application/json, text/plain, */*, application/octet-stream",
      "Content-Type": opts.contentType || "application/json; charset=UTF-8",
      "token": userInfo ? userInfo.token : "",
      "pversion": pversion
    } : {
      "X-Requested-With": "XMLHttpRequest",
      "Content-Type": opts.contentType || "application/json",
      "token": userInfo ? userInfo.token : "",
      "pversion": pversion
    }
  }
  // 转为formdata
  if(opts.contentType === "application/x-www-form-urlencoded; charset=UTF-8") {
    httpDefaultOpts.transformRequest = [function(data) {
      let ret = []
      for(let prop in data) {
        if(Array.isArray(data[prop])) {
          data[prop].map(p => {
            ret.push(`${encodeURIComponent(prop)}[]=${encodeURIComponent(p)}`)
          })
        } else {
          ret.push(`${encodeURIComponent(prop)}=${encodeURIComponent(data[prop])}`)
        }
      }
      return ret.join("&")
    }]
  }

  if(opts.method == "get" || opts.method == "delete") {
    delete httpDefaultOpts.data
  } else {
    httpDefaultOpts.url = httpDefaultOpts.url
    if(opts.contentType && opts.contentType !== "application/x-www-form-urlencoded; charset=UTF-8") { // 判断post请求条件下是否有特殊设置
      delete httpDefaultOpts.data
    } else {
      delete httpDefaultOpts.params
    }
  }

  let promise = new Promise((resolve, reject) => {
    axios(httpDefaultOpts).then(res => {
      if (
        res.data["code"] == 40001 ||
        res.data["code"] == 40002 ||
        res.data["code"] == 40003 ||
        res.data["code"] == 40004 ||
        res.data["code"] == 40005 ||
        res.data["code"] == 40011 ||
        res.data["code"] == 40012 ||
        res.data["code"] == 40013 ||
        res.data["code"] == 40014 ||
        res.data["code"] == 40015 ||
        res.data["code"] == 40016 ||
        res.data["code"] == -9999 ||
        res.data["code"] == 40017
      ) {
        logout();
      }
      resolve(res)
    }).catch(response => {
      if(
        response.data["code"] == 40001 ||
        response.data["code"] == 40002 ||
        response.data["code"] == 40003 ||
        response.data["code"] == 40004 ||
        response.data["code"] == 40005 ||
        response.data["code"] == 40011 ||
        response.data["code"] == 40012 ||
        response.data["code"] == 40013 ||
        response.data["code"] == 40014 ||
        response.data["code"] == 40015 ||
        response.data["code"] == 40016 ||
        response.data["code"] == -9999 ||
        response.data["code"] == 40017
      ) {
        return
      }
      errorState(response)
      reject(response)
    })
  })
  return promise
}

export default httpServer